import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Row, Col, Tooltip, Upload, Image } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { 
  addReadingRoom, 
  deleteReadingRoom, 
  updateReadingRoom, 
  listReadingRoom,
  ReadingRoomDetail 
} from '@/api/readingRoomController';
import { listReadingRoomReservation } from '@/api/readingRoomReservationController';
import { getUserInfoVo } from '@/api/userController';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd/es/upload';
import type { RcFile } from 'antd/es/upload/interface';

interface SeatStatus {
  id: number;
  number: number;
  status: number;
}

interface ReservationInfo {
  id: string;
  userid: string;
  roomid: string;
  seatnumber: number;
  starttime: string;
  endtime: string;
  status: number;
  createtime: string;
  updatetime: string;
  userInfo?: {
    id: string;
    nickName: string;
    email: string;
    avatarUrl: string;
    gender: number;
    address: string;
    userProfile: string;
    createTime: string;
    updateTime: string;
  };
}

export default function SeatManagement() {
  const [data, setData] = useState<ReadingRoomDetail[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [seatModalVisible, setSeatModalVisible] = useState(false);
  const [currentSeats, setCurrentSeats] = useState<SeatStatus[]>([]);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [reservations, setReservations] = useState<ReservationInfo[]>([]);
  const [uploadLoading, setUploadLoading] = useState(false);

  const fetchData = async () => {
    try {
      const response = await listReadingRoom();
      if (response.data) {
        setData(response.data);
      }
    } catch (error) {
      message.error('获取数据失败');
    }
  };

  const fetchReservations = async () => {
    try {
      const response = await listReadingRoomReservation();
      if (response.data) {
        const reservationsWithUserInfo = await Promise.all(
          response.data.map(async (reservation) => {
            try {
              const userInfo = await getUserInfoVo({ id: reservation.userid });
              return {
                ...reservation,
                userInfo: userInfo.data
              };
            } catch (error) {
              return reservation;
            }
          })
        );
        setReservations(reservationsWithUserInfo);
      }
    } catch (error) {
      message.error('获取预约信息失败');
    }
  };

  useEffect(() => {
    fetchData();
    fetchReservations();
  }, []);

  const showSeatStatus = (seatStatus: string) => {
    const seats = JSON.parse(seatStatus);
    setCurrentSeats(seats);
    setSeatModalVisible(true);
  };

  const generateSeatStatus = (totalSeats: number) => {
    const seats = [];
    for (let i = 1; i <= totalSeats; i++) {
      seats.push({
        id: i,
        number: i,
        status: 1  // 默认状态为1，表示空闲
      });
    }
    return JSON.stringify(seats);
  };

  const handleAdd = async (values: any) => {
    try {
      const totalSeats = parseInt(values.totalseats, 10);
      const submitData = {
        roomname: values.roomname,
        imageurl: values.imageurl,
        description: values.description,
        openinghours: values.openinghours,
        totalseats: totalSeats,
        seatstatus: generateSeatStatus(totalSeats)  // 添加座位状态数组
      };

      if (editingId) {
        const res = await updateReadingRoom({
          id: editingId,
          ...submitData,
        });
        if (res.code === 200) {
          message.success('修改成功');
          setIsModalVisible(false);
          form.resetFields();
          fetchData();
        } else {
          message.error(res.message || '修改失败');
        }
      } else {
        const res = await addReadingRoom(submitData);
        if (res.code === 200) {
          message.success('添加成功');
          setIsModalVisible(false);
          form.resetFields();
          fetchData();
        } else {
          message.error(res.message || '添加失败');
        }
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || '系统错误';
      message.error(errorMsg);
    }
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个阅览室吗？删除后不可恢复！',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteReadingRoom({ id });
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  const columns: ColumnsType<ReadingRoomDetail> = [
    {
      title: '阅览室ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '图片',
      dataIndex: 'imageurl',
      key: 'imageurl',
      width: 120,
      render: (imageurl: string) => (
        <Image
          src={imageurl}
          alt="阅览室图片"
          width={100}
          height={60}
          style={{ objectFit: 'cover' }}
        />
      ),
    },
    {
      title: '阅览室名称',
      dataIndex: 'roomname',
      key: 'roomname',
    },
    {
      title: '开放时间',
      dataIndex: 'openinghours',
      key: 'openinghours',
    },
    {
      title: '当前人数/总座位数',
      key: 'seats',
      render: (_, record) => `${record.currentcount}/${record.totalseats}`,
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      key: 'createtime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => showSeatStatus(record.seatstatus)}>
            查看座位
          </Button>
          <Button onClick={() => {
            setEditingId(record.id);
            form.setFieldsValue(record);
            setIsModalVisible(true);
          }}>
            编辑
          </Button>
          <Button danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const getReservationInfo = (roomId: string, seatNumber: number) => {
    return reservations.find(
      (r) => r.roomid === roomId && r.seatnumber === seatNumber
    );
  };

  const renderSeatMap = () => {
    const rows = [];
    for (let i = 0; i < currentSeats.length; i += 8) {
      rows.push(currentSeats.slice(i, i + 8));
    }

    const renderSeat = (seat: SeatStatus, roomId: string) => {
      const reservation = getReservationInfo(roomId, seat.number);
      const tooltipTitle = reservation ? (
        <div>
          <p>使用者：{reservation.userInfo?.nickName || '未知用户'}</p>
          <p>邮箱：{reservation.userInfo?.email}</p>
          <p>地址：{reservation.userInfo?.address}</p>
          <p>开始时间：{new Date(reservation.starttime).toLocaleString()}</p>
          <p>结束时间：{new Date(reservation.endtime).toLocaleString()}</p>
        </div>
      ) : '空闲座位';

      return (
        <Tooltip title={tooltipTitle} key={seat.id}>
          <Button
            type={seat.status === 1 ? 'primary' : 'default'}
            style={{ 
              margin: '5px', 
              width: '60px',
              backgroundColor: seat.status === 1 ? '#1890ff' : '#f5f5f5',
              color: seat.status === 1 ? 'white' : 'rgba(0, 0, 0, 0.25)',
              borderColor: seat.status === 1 ? '#1890ff' : '#d9d9d9',
              cursor: 'default'
            }}
            disabled={true}
          >
            {seat.number}
          </Button>
        </Tooltip>
      );
    };

    return (
      <div style={{ padding: '20px' }}>
        {rows.map((row, rowIndex) => (
          <Row key={rowIndex} style={{ marginBottom: '10px' }}>
            <Col span={8}>
              <div style={{ display: 'flex', justifyContent: 'flex-start', gap: '10px' }}>
                {row.slice(0, 3).map(seat => renderSeat(seat, data[0]?.id))}
              </div>
            </Col>
            
            <Col span={8}>
              <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>
                {row.slice(3, 5).map(seat => renderSeat(seat, data[0]?.id))}
              </div>
            </Col>
            
            <Col span={8}>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
                {row.slice(5, 8).map(seat => renderSeat(seat, data[0]?.id))}
              </div>
            </Col>
          </Row>
        ))}
      </div>
    );
  };

  // 图片上传相关函数
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setUploadLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setUploadLoading(false);
        const imageUrl = info.file.response.data;
        form.setFieldsValue({ imageurl: imageUrl });
        message.success('图片上传成功！');
      } else {
        setUploadLoading(false);
        message.error(info.file.response.message || '图片上传失败！');
      }
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          onClick={() => {
            setEditingId(null);
            form.resetFields();
            setIsModalVisible(true);
          }}
        >
          添加阅览室
        </Button>
      </div>
      
      <Table columns={columns} dataSource={data} rowKey="id" />

      <Modal
        title={editingId ? "编辑阅览室" : "添加阅览室"}
        open={isModalVisible}
        onOk={form.submit}
        okText="确认"
        cancelText="取消"
        onCancel={() => setIsModalVisible(false)}
        width={800}
      >
        <Form
          form={form}
          onFinish={handleAdd}
          layout="vertical"
        >
          <Form.Item
            name="roomname"
            label="阅览室名称"
            rules={[
              { required: true, message: '阅览室名称不能为空' },
              { min: 2, max: 50, message: '阅览室名称长度必须在2-50个字符之间' }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="阅览室介绍"
            rules={[
              { required: true, message: '阅览室介绍不能为空' },
              { max: 500, message: '阅览室介绍长度不能超过500个字符' }
            ]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item
            name="openinghours"
            label="开放时间"
            rules={[
              { required: true, message: '开放时间不能为空' },
              {
                pattern: /^周[一二三四五六日]至周[一二三四五六日] \|\d{1,2}:\d{2}-\d{1,2}:\d{2}$/,
                message: '请按照格式填写，如：周一至周日 |8:00-22:00'
              }
            ]}
          >
            <Input placeholder="格式：周一至周日 |8:00-22:00" />
          </Form.Item>

          <Form.Item
            name="totalseats"
            label="总座位数"
            rules={[
              { required: true, message: '总座位数不能为空' },
              {
                validator: async (_, value) => {
                  const num = parseInt(value, 10);
                  if (isNaN(num)) {
                    throw new Error('请输入有效的数字');
                  }
                  if (num < 1) {
                    throw new Error('总座位数必须大于0');
                  }
                  if (num > 120) {
                    throw new Error('总座位数不能超过120');
                  }
                }
              }
            ]}
          >
            <Input type="number" min={1} max={120} />
          </Form.Item>

          <Form.Item 
            label="阅览室图片" 
            required 
            tooltip="支持 jpg/png 格式，大小不超过 2MB"
          >
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              action="http://localhost:8081/api/file/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              data={{ biz: 'reading_room_image' }}
              withCredentials={true}
            >
              {form.getFieldValue('imageurl') ? (
                <Image 
                  src={form.getFieldValue('imageurl')} 
                  alt="阅览室图片" 
                  width="100%"
                  height="100%"
                  style={{ objectFit: 'cover' }}
                  preview={false}
                />
              ) : (
                <div>
                  {uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              )}
            </Upload>
            <Form.Item 
              name="imageurl" 
              hidden
              rules={[{ required: true, message: '请上传阅览室图片' }]}
            >
              <Input />
            </Form.Item>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="座位分布图"
        open={seatModalVisible}
        onCancel={() => setSeatModalVisible(false)}
        width={1000}
        footer={null}
      >
        {renderSeatMap()}
        <div style={{ marginTop: 16 }}>
          <span style={{ marginRight: 16 }}>
            <Button
              disabled
              style={{
                backgroundColor: '#1890ff',
                color: 'white',
                borderColor: '#1890ff'
              }}
            >
              空闲
            </Button> 空闲座位
          </span>
          <span>
            <Button
              disabled
              style={{
                backgroundColor: '#f5f5f5',
                color: 'rgba(0, 0, 0, 0.25)',
                borderColor: '#d9d9d9'
              }}
            >
              占用
            </Button> 已占用座位
          </span>
        </div>
      </Modal>
    </div>
  );
} 